package sunshine.commcon.util.minio;

import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class MinIOService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;
    
    /**
     * 检查存储桶是否存在，如果不存在则创建它
     *
     * @throws Exception 当创建存储桶过程中发生错误时抛出异常
     */
    public void createBucketIfNotExists() throws Exception {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("存储桶检查/创建失败: " + e.getMessage());
        }
    }

    /**
     * 上传文件到MinIO存储服务
     *
     * @param file 要上传的文件，封装在MultipartFile对象中
     * @return 返回文件的预签名访问URL，有效期为7天
     * @throws Exception 当文件上传过程中发生错误时抛出异常
     */
    public String uploadFile(MultipartFile file) throws Exception {
        try {
            // 生成唯一的对象名称，避免文件名冲突
            String objectName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 上传文件到 MinIO
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(args);

            // 返回访问 URL
            // 如果是 public 桶，可以直接访问：http://localhost:9000/user-images/filename.jpg
            return minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketName)
                            .object(objectName)
/*                             .expiry(36500, TimeUnit.DAYS) // 签名链接有效期 7 天*/
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

}